<?php

namespace frontendw\models;

use common\models\User;
use yii\base\InvalidParamException;
use yii\base\Model;
use Yii;

/**
 * Password reset form
 */
class ResetPasswordForm extends Model {

    public $password;
    public $repassword;
    public $oldpassword;

    /**
     * @var \common\models\User
     */
    private $_user;

    /**
     * Creates a form model given a token.
     *
     * @param  string                          $token
     * @param  array                           $config name-value pairs that will be used to initialize the object properties
     * @throws \yii\base\InvalidParamException if token is empty or not valid
     */
    public function __construct($token, $config = []) {
        $this->_user = User::findOne($token);
        if (!$this->_user) {
            throw new InvalidParamException('Wrong password reset token.');
        }
        parent::__construct($config);
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['password','oldpassword'], 'required', "message" => "密码不能为空"],
            [['password'], 'string', 'min' => 6],
            ['oldpassword', 'validatePassword'],
            [["repassword"], "compare", "compareAttribute" => "password", "message" => "两次密码不一致"],
        ];
    }

    /**
     * Resets password.
     *
     * @return boolean if password was reset.
     */
    public function resetPassword() {
        $user = $this->_user;
        $user->setPassword($this->password);
        $user->removePasswordResetToken();

        return $user->save(false);
    }

    public function validatePassword($attribute, $params) {
        if (!$this->hasErrors()) {
            if (!$this->_user || !$this->_user->validatePassword($this->oldpassword)) {
                $this->addError($attribute, '您输入的密码不正确');
            }
        }
    }

}
